﻿using XW.Utils;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Identity;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime;
using System.Text;
using System.Threading.Tasks;
//using XW.Core.Tools;

namespace XW.Core;


/// <summary>
/// SqlSugar仓储类
/// </summary>
/// <typeparam name="T"></typeparam>
public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
{
    protected ITenant iTenant = null; // 多租户事务

    public SqlSugarRepository(ISqlSugarClient context = null) : base(context)
    {
        iTenant = SXHttpContext.GetService<ISqlSugarClient>().AsTenant();

        // 若实体贴有多库特性，则返回指定的连接
        if (typeof(T).IsDefined(typeof(TenantAttribute), false))
        {
            Context = iTenant.GetConnectionScopeWithAttr<T>().CopyNew();
            return;
        }

        // 若实体贴有系统表特性，则返回默认的连接
        if (typeof(T).IsDefined(typeof(SystemTableAttribute), false))
        {
            Context = iTenant.GetConnectionScope(App.DB_DEFAULT_CONN_NAME).CopyNew();
            return;
        }

        // 若当前未登录或是默认租户Id，则返回默认的连接
        //var tenantId = XWContext.TenantId;
        //if (tenantId < 1 || tenantId.ToString() == App.DB_DEFAULT_CONN_NAME) return;

        //var tenant = CacheHelper.Get<List<SysTenant>>(CacheConst.KeyTenant).FirstOrDefault(u => u.Id == tenantId);
        //if (tenant is null || tenant is { TenantType: TenantTypeEnum.Id }) return;

        //// 根据租户Id切库
        //if (!iTenant.IsAnyConnection(tenantId.ToString()))
        //{
        //    // 获取主库连接配置
        //    var configs = ConfigHelper.GetDB();
        //    var mainConnConfig = configs.First(u => u.ConfigId == SqlSugarConst.ConfigId);

        //    // 连接配置
        //    var connectionConfig = new DbConnectionConfig
        //    {
        //        ConfigId = tenant.Id,
        //        DbType = tenant.DbType,
        //        IsAutoCloseConnection = true,
        //        ConnectionString = tenant.Connection,
        //        DbSettings = new DbSettings()
        //        {
        //            EnableUnderLine = mainConnConfig.DbSettings.EnableUnderLine,
        //        }
        //    };
        //    iTenant.AddConnection(connectionConfig);
        //    SqlSugarServiceExtent.SetDbConfig(connectionConfig);
        //    SqlSugarServiceExtent.SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()));
        //}
        //Context = iTenant.GetConnectionScope(tenantId.ToString()).CopyNew();
    }
}
